#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <error.h>
#include <stdio.h>
#include <sys/epoll.h>
#include "tlv.h"
#include <unistd.h>

int tcp_init(const char *ip,const char *port);

void *response(tlv_t *tlv,int sockfd,uint8_t type,uint32_t length,const uint8_t *value){
    printf("type=%d,length=%d,value=%s\n",type,length,value);
    char message_response[]="i got it.";
    tlv_response(tlv,sockfd,sizeof(message_response),(uint8_t*)message_response);
    return NULL;
}

int main(int argc, char *argv[])
{
    if(argc!=3){

        exit(EXIT_FAILURE);
    }

    int sockfd;
    if((sockfd=tcp_init(argv[1],argv[2]))==-1){fprintf(stderr,"tcp init occur error\n");}
    
    int clientfd;
    if((clientfd=accept(sockfd,NULL,NULL))==-1){fprintf(stderr,"accept");};
    printf("clientfd=%d\n",clientfd);

    tlv_t tlv;
    while(1){
        tlv_listen(&tlv,clientfd,response);
        sleep(1);
    }

    return 0;
}


int tcp_init(const char *ip,const char *port){
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd==-1){
        perror("socket");
        return -1;
    }

    int flag;
    socklen_t optlen=sizeof(flag);
    if(getsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,&optlen)==-1){
        perror("getsockopt");
        return -1;
    }
    flag=1;
    if(setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,optlen)==-1){
        perror("setsockopt");
        return -1;
    }

    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=inet_addr(ip);
    addr.sin_port=htons(atoi(port));
    if(bind(sockfd,(struct sockaddr*)&addr,sizeof(addr))==-1){
        perror("bind");
        return -1;
    }

    if(listen(sockfd,10)==-1){
        perror("listen");
        return -1;
    }

    return sockfd;
}
